#!/usr/bin/env php
<?php
/**
 * GenIt, Code generator for Cubi Application Platform
 *
 * Based on gen_meta.php By Rocky Swen
 * LICENSE
 *
 * This source file is subject to the BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @package   openbiz.bin.lib
 * @copyright Copyright (c) 2005-2011, Rocky Swen, Agus Suhartono
 * @license   http://www.opensource.org/licenses/bsd-license.php
 * @link      http://www.phpopenbiz.org/
 * @version   $Id$
 */

include_once dirname(dirname(__FILE__)) . "/app_init.php";
//include_once dirname(__FILE__)."/require_auth.php";
include_once dirname(__FILE__) . "/genit.inc.php";

if (!defined("CLI")) {
    exit;
}

if ($argc < 1) {
    echo "usage: php gen_meta.php dbname table [modulename] [metadata template set]" . PHP_EOL;
    exit;
}

if ($argc = 1) {
    $db_name = null;
    $table_name = $argv[1];
    $package_name = null;
    $options = null;
} else {

    $db_name = $argv[1];

    $table_name = $argv[2]; // database table name

    $package_name = isset($argv[3]) ? $argv[3] : $table_name;
    $meta_tpl = isset($argv[4]) ? $argv[4] : "metatpl";
    
    define("META_TPL", $meta_tpl);

    $package_directory = MODULE_PATH . DIRECTORY_SEPARATOR . str_replace(".", DIRECTORY_SEPARATOR, $package_name);

    $namings = GenitHelper::generateNamingList($table_name, $package_name);
    printDataNaming($namings);
    $options = GenitHelper::readNamingOption($namings);

    $acl = GenitHelper::readSelectedAccessControl();

// check if the /modules/table is already there
    echo PHP_EOL . "---------------------------------------" . PHP_EOL;
    echo "Target dir: $options[0]" . PHP_EOL;
    echo "Medata file to create: " . PHP_EOL;
    echo "  do/$options[1]DO.xml" . PHP_EOL;
    echo "  form/$options[1]...Form.xml" . PHP_EOL;
    echo "  view/$options[1]View.xml" . PHP_EOL;
    echo "Do you want to continue? [y/n] (y) : ";
    // Read the input
    $answer = trim(fgets(STDIN));
    $answer = $answer ? $answer : "y";
    if (strtolower($answer) != 'y')
        exit;
}

//print_r($opts);
    $metaGen = new MetaGenerator($package_name, $db_name, $table_name, $options);

$metaGen->setACL($acl);
define("META_TPL", $metaGen->templateDir);
$options = $metaGen->options;

if ($metaGen->isAutoGenerate) {
    echo "Generate Data Object metadata file ..." . PHP_EOL;
    $metaGen->genDOMeta();
} else {
// create do xml
    echo "---------------------------------------" . PHP_EOL;
    echo "Do you want to generate data Object? [y/n] (y) : ";
    $answer = trim(fgets(STDIN));
    $answer = $answer ? $answer : "y";
    if (strtolower($answer) == 'y') {
        echo "Generate Data Object metadata file ..." . PHP_EOL;
        $metaGen->genDOMeta();
    }
}

// create forms xml
if ($metaGen->isAutoGenerate) {
    echo "Generate Form Object metadata files ..." . PHP_EOL;
    $metaGen->genFormMeta();
} else {
    echo "---------------------------------------" . PHP_EOL;
    echo "Do you want to generate form Object? [y/n] (y) : ";
    $answer = trim(fgets(STDIN));
    $answer = $answer ? $answer : "y";
    if (strtolower($answer) == 'y') {
        echo "Generate Form Object metadata files ..." . PHP_EOL;
        $metaGen->genFormMeta();
    }
}

// create view xml
if ($metaGen->isAutoGenerate) {
    echo "Generate view Object metadata files ..." . PHP_EOL;
    $metaGen->genViewMeta();
} else {
    echo "---------------------------------------" . PHP_EOL;
    echo "Do you want to generate view Object? [y/n] (y) : ";
// Read the input
    $answer = trim(fgets(STDIN));
    $answer = $answer ? $answer : "y";
    if (strtolower($answer) == 'y') {
        echo "Generate view Object metadata files ..." . PHP_EOL;
        $metaGen->genViewMeta();
    }
}

if ($metaGen->isAutoGenerate) {
    echo "Generate Module Dashboard ..." . PHP_EOL;
    $metaGen->genDashboardXML();
} else {
    echo "---------------------------------------" . PHP_EOL;
    echo "Do you want to generate module dashboard files? [y/n] (y) : ";
// Read the input
    $answer = trim(fgets(STDIN));
    $answer = $answer ? $answer : "y";
    if (strtolower($answer) == 'y') {
        // create mod.xml
        echo "Generate Module Dashboard ..." . PHP_EOL;
        $metaGen->genDashboardXML();
    }
}


//$sdd= subs
//detects if mod.xml exists
$modFolder = GenitHelper::getModuleName(strtolower($metaGen->options[3]));
//$package_directory = packageToPath($packageName)
$modFile = $package_directory = MODULE_PATH . "/" . $modFolder . "/mod.xml";
if (file_exists($modFile)) {
    if ($metaGen->isAutoGenerate) {
        echo "Modify mod.xml ..." . PHP_EOL;
        $metaGen->modifyModXML();
    } else {
        echo "---------------------------------------" . PHP_EOL;
        echo "Do you want to modify mod.xml? [y/n] (y) : ";
        // Read the input
        $answer = trim(fgets(STDIN));
        $answer = $answer ? $answer : "y";
        if (strtolower($answer) == 'y') {
            // create mod.xml
            echo "Modify mod.xml ..." . PHP_EOL;
            $metaGen->modifyModXML();
        }
    }
} else {
    if ($metaGen->isAutoGenerate) {
        echo "Generate mod.xml ..." . PHP_EOL;
        $metaGen->genModXML();
    } else {
        echo "---------------------------------------" . PHP_EOL;
        echo "Do you want to create mod.xml? [y/n] (y) : ";
        // Read the input
        $answer = trim(fgets(STDIN));
        $answer = $answer ? $answer : "y";
        if (strtolower($answer) == 'y') {
            // create mod.xml
            echo "Generate mod.xml ..." . PHP_EOL;
            $metaGen->genModXML();
        }
    }
}

/*
  $tmplist = explode('.',$opts[3]);
  $compName = $tmplist[0];
  echo "---------------------------------------".PHP_EOL;
  echo "Do you want to load this module $compName now? [y/n] (y) : ";
  // Read the input
  $answer = trim(fgets(STDIN));
  $answer = $answer?$answer:"y";
  if (strtolower($answer) == 'y'){
  // create mod.xml
  echo "Load module : ".$compName." ...".PHP_EOL;
  $script = dirname(__FILE__)."/load_module.php";
  $cmd = "$script ".$compName;
  exec($cmd,$output);
  $result = implode("\n", $output );
  echo $result."\n";
  }
 */

function generateNamingList($table_name, $package_name) {
// help user to set the metadata namings
    $temp = explode("_", $table_name);

    // modules/module-name/path/path
    $package_directory = MODULE_PATH . DIRECTORY_SEPARATOR . str_replace(".", DIRECTORY_SEPARATOR, $package_name);

    for ($i = 0; $i < count($temp); $i++) {
        $namings[$i] = array(
            $package_directory,
            GenitHelper::getCompName($table_name, $i),
            GenitHelper::getCompDisplayName($table_name, $i),
            $package_name);
    }
    return $namings;
}


/**
 * readNamingOption()
 * 
 * $opt[0] : package/module path (module/path/path<br />
 * $opt[1] : base Object name<br />
 * $opt[2] : module name / base Object description<br />
 * $opt[3] : package/module name (module-name.path.path)<br />
 * 
 * 
 * @param type $namings
 * @return array
 */
function readNamingOption($namings) {

    for ($i = 0; $i < count($namings); $i++) {
        $ques[] = $i + 1;
    }

    $n = 0;
    while (1) {
        $selection = trim(fgets(STDIN));
        $answer = intval($selection) - 1;

        // read custom 
        if (strtolower($selection) == 's') {
            echo "Please set a module path: "; // package/module path
            $package_name = trim(fgets(STDIN));
            $customOptions[0] = MODULE_PATH . DIRECTORY_SEPARATOR . trim($package_name);

            echo "Please set the component name: "; // base Object name
            $customOptions[1] = trim(fgets(STDIN));

            echo "Please set the component display name: ";
            $customOptions[2] = trim(fgets(STDIN));

            echo "Please set the module name: ";
            $customOptions[3] = trim(fgets(STDIN));
            $package_name = $customOptions[3];

            if ($customOptions[0] && $customOptions[1]) {
                break;
            }
        } else {
            $answer = $answer > -1 ? $answer : 0;
            if (!isset($namings[$answer]) && $n++ < 3)
                echo "Please select again: [" . implode("/", $ques) . "/s] : ";
            else
                break;
        }
    }


    if ($n > 3)
        exit;
    if (is_array($customOptions)) {
        $options = $customOptions;
    } else {
        $options = $namings[$answer];
    }

    return $options;
}

/**
 * readSelectedAccessControl()
 * <br />
 * 1. Access and Manage (default)" <br />
 * 2. Access, Create, Update and Delete" <br />
 * 3. No access control" <br />
 * 
 * @return number
 */
function readSelectedAccessControl() {
    echo PHP_EOL . "Access control options: " . PHP_EOL;
    echo "1. Access and Manage (default)" . PHP_EOL;
    echo "2. Access, Create, Update and Delete" . PHP_EOL;
    echo "3. No access control" . PHP_EOL;
    echo "Please select access control type [1/2/3] (1) : ";
    $acl = trim(fgets(STDIN));
    $acl = $acl ? $acl : "1";
    return $acl;
}

function packageToPath($packageName) {
    return MODULE_PATH . DIRECTORY_SEPARATOR . str_replace(".", DIRECTORY_SEPARATOR, $packageName);
}
?>
